package days46.title402;

import org.junit.Test;

import java.util.ArrayDeque;

public class Solution {
    // @Test
    // public void test(){
    //     removeKdigits("10200",1);
    // }
    public String removeKdigits(String num, int k) {
        if (num.length() == k) {
            return "0";
        }
        ArrayDeque<Character> integers = new ArrayDeque<>();
        for (int i = 0; i < num.length(); i++) {
            if (k == 0) {
                integers.push(num.charAt(i));
                continue;
            }
            if (integers.isEmpty()||integers.peek() < num.charAt(i)){
                integers.push(num.charAt(i));
                continue;
            }
            while (!integers.isEmpty()&&k>0&&integers.peek() > num.charAt(i)){
                integers.pop();
                k--;
            }
            integers.push(num.charAt(i));

        }
        while (k > 0) {
            integers.pop();
            k--;
        }
        StringBuilder stringBuilder = new StringBuilder();
        while (!integers.isEmpty()) {
            stringBuilder.append(integers.pop());
        }
        stringBuilder.reverse();
        while (!stringBuilder.isEmpty() && stringBuilder.charAt(0) == '0') {
            stringBuilder.deleteCharAt(0);
        }
        if (stringBuilder.isEmpty()) {
            return "0";
        }
        return stringBuilder.toString();
    }
}